﻿using Microsoft.Extensions.Caching.StackExchangeRedis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using PmSoft.Cache.Abstractions.EntityCache;
using StackExchange.Redis;
using System.Net;

namespace PmSoft.Cache.Redis;

public static class ServiceCollectionExtensions
{
    /// <summary>
    /// 添加 Redis 缓存服务。
    /// </summary>
    /// <param name="services">服务集合。</param>
    /// <param name="configuration">配置对象，用于读取 Redis 缓存配置。</param>
    /// <returns>服务集合。</returns>
    /// <exception cref="ArgumentNullException">当 <paramref name="services"/> 或 <paramref name="configuration"/> 为 null 时抛出。</exception>
    public static IServiceCollection AddRedisCache(this IServiceCollection services, IConfiguration configuration)
    {
        if (services == null) throw new ArgumentNullException(nameof(services));
        if (configuration == null) throw new ArgumentNullException(nameof(configuration));

        // 配置 Redis 缓存选项
        services.Configure<RedisCacheOptions>(configuration.GetSection("RedisCacheOptions"));

		//添加分布式缓存
		services.AddStackExchangeRedisCache(options =>
		{
			var endPoints = configuration.GetSection("RedisCacheOptions:ConfigurationOptions:EndPoints")
			.Get<string[]>()?
			.Select(m => EndPointCollection.TryParse(m)) ?? new List<EndPoint>();
			foreach (var endPoint in endPoints)
			{
				if (endPoint != null)
					options.ConfigurationOptions?.EndPoints.Add(endPoint);
			}
		});
 
		// 注册 Redis 缓存提供者
		services.TryAddSingleton<IRedisCacheProvider, RedisCacheProvider>();

		// 注册 Redis 实体缓存服务
		services.TryAddSingleton(typeof(IDistributedEntityCacheVersionService<,>), typeof(RedisEntityCacheVersionService<,>));
		return services;
	}
 
}